"""
    User API
    @author: Jean-Lou Dupont
"""

import os
import sys
import logging
import string

import wsgiref.handlers
from google.appengine.ext import webapp
from google.appengine.api import users

from string import Template

class UserApiHandler(webapp.RequestHandler):
    
    _template = """
        {
            "username":"$username",
            "groups":"$group_admin",
            "login_url" :"$login_url",
            "logout_url":"$logout_url"
        }    
    """
    
    def get(self, dst):
        user = users.get_current_user()
        group_admin = ''
        username = ''        
        login_url   = users.create_login_url(dst)
        logout_url  = users.create_logout_url(dst)        

        if user:
            username = user.nickname()
            if (users.is_current_user_admin()):
                group_admin = 'admin'

        tpl = Template(UserApiHandler._template)

        template_values = { 'username':     username, 
                            'group_admin':  group_admin,
                            'login_url':    login_url,
                            'logout_url':   logout_url
                            };
        
        try:
            self.response.out.write( tpl.substitute(template_values) )
            self.response.headers["Content-Type"]  = "application/json"
            self.response.headers['Cache-Control'] = 'no-cache, must-revalidate, max-age=0'
            logging.info("/api/user/ user[%s]" % username)
        except Exception,e:
            logging.info("/api/user/ EXCEPTION, msg=%s" % e)
            self.response.set_status( 404 )
        
#========================================================================================================
def main():
  application = webapp.WSGIApplication([('/api/user/(.*)/',UserApiHandler) ], debug=True)
  wsgiref.handlers.CGIHandler().run(application)

if __name__ == "__main__":
    main()        